import React, { useState } from 'react';
import { 
  Card, 
  Tabs, 
  Upload, 
  Button, 
  Space, 
  Image, 
  Tag, 
  Input, 
  Select,
  Row,
  Col,
  Modal,
  Form,
  message,
  Tooltip,
  Popconfirm
} from 'antd';
import { 
  PlusOutlined, 
  UploadOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined,
  FolderOutlined,
  FileImageOutlined,
  FileTextOutlined
} from '@ant-design/icons';

const { Option } = Select;
const { Search } = Input;
const { TabPane } = Tabs;

interface Material {
  id: string;
  name: string;
  type: 'image' | 'video' | 'text';
  size: string;
  category: string;
  tags: string[];
  uploadTime: string;
  url: string;
}

interface Draft {
  id: string;
  title: string;
  content: string;
  images: string[];
  status: 'draft' | 'review' | 'ready';
  createTime: string;
  updateTime: string;
}

const Content: React.FC = () => {
  const [materials, setMaterials] = useState<Material[]>([
    {
      id: '1',
      name: 'product_image_1.jpg',
      type: 'image',
      size: '2.5MB',
      category: '产品图',
      tags: ['美妆', '护肤'],
      uploadTime: '2024-01-15 14:30:00',
      url: 'https://via.placeholder.com/300x200'
    },
    {
      id: '2',
      name: 'lifestyle_video.mp4',
      type: 'video',
      size: '15.2MB',
      category: '生活视频',
      tags: ['生活', '日常'],
      uploadTime: '2024-01-14 10:15:00',
      url: 'https://via.placeholder.com/300x200'
    }
  ]);

  const [drafts, setDrafts] = useState<Draft[]>([
    {
      id: '1',
      title: '春季护肤攻略',
      content: '春季护肤的重点是补水和防晒...',
      images: ['https://via.placeholder.com/150x100'],
      status: 'draft',
      createTime: '2024-01-15 14:30:00',
      updateTime: '2024-01-15 16:45:00'
    },
    {
      id: '2',
      title: '美妆产品推荐',
      content: '今天给大家推荐几款性价比超高的美妆产品...',
      images: ['https://via.placeholder.com/150x100', 'https://via.placeholder.com/150x100'],
      status: 'ready',
      createTime: '2024-01-14 09:20:00',
      updateTime: '2024-01-15 11:30:00'
    }
  ]);

  const [isMaterialModalVisible, setIsMaterialModalVisible] = useState(false);
  const [isDraftModalVisible, setIsDraftModalVisible] = useState(false);
  const [editingDraft, setEditingDraft] = useState<Draft | null>(null);
  const [form] = Form.useForm();

  const getStatusTag = (status: string) => {
    const statusConfig = {
      draft: { color: 'orange', text: '草稿' },
      review: { color: 'blue', text: '审核中' },
      ready: { color: 'green', text: '待发布' }
    };
    const config = statusConfig[status as keyof typeof statusConfig];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const getTypeIcon = (type: string) => {
    return type === 'image' ? <FileImageOutlined /> : <FileTextOutlined />;
  };

  const handleMaterialUpload = (info: any) => {
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    }
  };

  const handleDraftEdit = (draft: Draft) => {
    setEditingDraft(draft);
    form.setFieldsValue(draft);
    setIsDraftModalVisible(true);
  };

  const handleDraftDelete = (id: string) => {
    setDrafts(drafts.filter(draft => draft.id !== id));
    message.success('草稿删除成功');
  };

  const handleDraftModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingDraft) {
        // 更新草稿
        setDrafts(drafts.map(draft => 
          draft.id === editingDraft.id 
            ? { ...draft, ...values, updateTime: new Date().toLocaleString() }
            : draft
        ));
        message.success('草稿更新成功');
      } else {
        // 添加新草稿
        const newDraft: Draft = {
          id: Date.now().toString(),
          ...values,
          images: [],
          status: 'draft',
          createTime: new Date().toLocaleString(),
          updateTime: new Date().toLocaleString()
        };
        setDrafts([...drafts, newDraft]);
        message.success('草稿创建成功');
      }
      setIsDraftModalVisible(false);
      setEditingDraft(null);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const MaterialManagement = () => (
    <div>
      <Card
        title="素材管理"
        extra={
          <Space>
            <Upload
              name="file"
              action="/api/upload"
              onChange={handleMaterialUpload}
              showUploadList={false}
            >
              <Button icon={<UploadOutlined />}>上传素材</Button>
            </Upload>
            <Button type="primary" icon={<PlusOutlined />}>
              新建文件夹
            </Button>
          </Space>
        }
      >
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <Search placeholder="搜索素材" allowClear />
          </Col>
          <Col span={4}>
            <Select placeholder="素材类型" allowClear style={{ width: '100%' }}>
              <Option value="image">图片</Option>
              <Option value="video">视频</Option>
              <Option value="text">文本</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Select placeholder="分类" allowClear style={{ width: '100%' }}>
              <Option value="产品图">产品图</Option>
              <Option value="生活视频">生活视频</Option>
              <Option value="文案">文案</Option>
            </Select>
          </Col>
        </Row>

        <Row gutter={[16, 16]}>
          {materials.map(material => (
            <Col span={6} key={material.id}>
              <Card
                hoverable
                cover={
                  <div style={{ height: 150, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Image
                      width="100%"
                      height={150}
                      src={material.url}
                      style={{ objectFit: 'cover' }}
                    />
                  </div>
                }
                actions={[
                  <Tooltip title="预览">
                    <EyeOutlined key="view" />
                  </Tooltip>,
                  <Tooltip title="下载">
                    <DownloadOutlined key="download" />
                  </Tooltip>,
                  <Tooltip title="删除">
                    <Popconfirm
                      title="确定要删除这个素材吗？"
                      onConfirm={() => {
                        setMaterials(materials.filter(m => m.id !== material.id));
                        message.success('素材删除成功');
                      }}
                    >
                      <DeleteOutlined key="delete" />
                    </Popconfirm>
                  </Tooltip>
                ]}
              >
                <Card.Meta
                  title={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      {getTypeIcon(material.type)}
                      <span style={{ marginLeft: 8 }}>{material.name}</span>
                    </div>
                  }
                  description={
                    <div>
                      <div>大小: {material.size}</div>
                      <div>分类: {material.category}</div>
                                             <div style={{ marginTop: 8 }}>
                         {material.tags.map(tag => (
                           <Tag key={tag}>{tag}</Tag>
                         ))}
                       </div>
                    </div>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>
      </Card>
    </div>
  );

  const DraftManagement = () => (
    <div>
      <Card
        title="草稿箱"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={() => {
            setEditingDraft(null);
            form.resetFields();
            setIsDraftModalVisible(true);
          }}>
            新建草稿
          </Button>
        }
      >
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <Search placeholder="搜索草稿" allowClear />
          </Col>
          <Col span={4}>
            <Select placeholder="状态筛选" allowClear style={{ width: '100%' }}>
              <Option value="draft">草稿</Option>
              <Option value="review">审核中</Option>
              <Option value="ready">待发布</Option>
            </Select>
          </Col>
        </Row>

        <Row gutter={[16, 16]}>
          {drafts.map(draft => (
            <Col span={8} key={draft.id}>
              <Card
                hoverable
                actions={[
                  <Tooltip title="编辑">
                    <EditOutlined key="edit" onClick={() => handleDraftEdit(draft)} />
                  </Tooltip>,
                  <Tooltip title="预览">
                    <EyeOutlined key="view" />
                  </Tooltip>,
                  <Tooltip title="删除">
                    <Popconfirm
                      title="确定要删除这个草稿吗？"
                      onConfirm={() => handleDraftDelete(draft.id)}
                    >
                      <DeleteOutlined key="delete" />
                    </Popconfirm>
                  </Tooltip>
                ]}
              >
                <Card.Meta
                  title={
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                      <span>{draft.title}</span>
                      {getStatusTag(draft.status)}
                    </div>
                  }
                  description={
                    <div>
                      <div style={{ marginBottom: 8 }}>
                        {draft.content.length > 50 
                          ? `${draft.content.substring(0, 50)}...` 
                          : draft.content
                        }
                      </div>
                      {draft.images.length > 0 && (
                        <div style={{ marginBottom: 8 }}>
                          <Image.PreviewGroup>
                            <Space>
                              {draft.images.map((img, index) => (
                                <Image
                                  key={index}
                                  width={60}
                                  height={40}
                                  src={img}
                                  style={{ objectFit: 'cover' }}
                                />
                              ))}
                            </Space>
                          </Image.PreviewGroup>
                        </div>
                      )}
                      <div style={{ fontSize: '12px', color: '#666' }}>
                        <div>创建时间: {draft.createTime}</div>
                        <div>更新时间: {draft.updateTime}</div>
                      </div>
                    </div>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>
      </Card>
    </div>
  );

  return (
    <div>
      <Tabs defaultActiveKey="materials">
        <TabPane tab="素材管理" key="materials">
          <MaterialManagement />
        </TabPane>
        <TabPane tab="草稿箱" key="drafts">
          <DraftManagement />
        </TabPane>
      </Tabs>

      {/* 草稿编辑模态框 */}
      <Modal
        title={editingDraft ? '编辑草稿' : '新建草稿'}
        open={isDraftModalVisible}
        onOk={handleDraftModalOk}
        onCancel={() => {
          setIsDraftModalVisible(false);
          setEditingDraft(null);
        }}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="请输入草稿标题" />
          </Form.Item>
          
          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: '请输入内容' }]}
          >
            <Input.TextArea 
              rows={6} 
              placeholder="请输入草稿内容"
              showCount
              maxLength={1000}
            />
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
          >
            <Select>
              <Option value="draft">草稿</Option>
              <Option value="review">审核中</Option>
              <Option value="ready">待发布</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Content; 